package leetcode_二分查找;

import java.util.Arrays;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 * 算法：二分查找
 *
 * @author yezh
 * @date 2024/3/6 15:17
 */
public class _34 {

    public static void main(String[] args) {
        int[] nums = {1};
        int target = 1;
        int[] ints = new _34().searchRange(nums, target);
        System.out.println(Arrays.toString(ints));
    }

    public int[] searchRange(int[] nums, int target) {
        int[] ans = new int[2];
        int n = nums.length;
        int res = boundSearch(nums, target);
        ans[0] = res >= n || nums[res] != target ? -1 : res;
        if (ans[0] == -1) ans[1] = -1;
        else {
            res = boundSearch(nums, target + 1);
            ans[1] = res == 0 && nums[res] == target ? res : res - 1;
        }
        return ans;
    }

    int boundSearch(int[] nums, int target) {
        int l = 0, r = nums.length - 1, mid;
        while (l <= r) {
            mid = l + (r - l) / 2;
            if (target > nums[mid]) l = mid + 1;
            else r = mid - 1;
        }
        return l;
    }

}
